package cn.script.fxj.bind.utils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author 周永波
 */
public class BindRectField {

    /**
     * 获取包括父类在内的指定字段
     *
     * @param fieldName
     * @param clazz
     * @return
     */
    public static Field getFieldSupper(String fieldName, Class clazz) {
        Field declaredField = null;
        try {
            declaredField = clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            clazz = clazz.getSuperclass();
            if (clazz == null) {
                return null;
            }
            declaredField = getFieldSupper(fieldName, clazz);
        }
        return declaredField;
    }

    /**
     * 根据字段取值
     *
     * @param o
     * @param fieldName
     * @param <T>
     * @return
     */
    public static <T> T getBeanField(Object o, String fieldName) {
        if (o instanceof Map) {
            return (T) ((Map) o).get(fieldName);
        }
        Class<?> aClass = o.getClass();
        try {
            Field declaredField = getFieldSupper(fieldName, aClass);
            if (declaredField == null) {
                return null;
            }
            declaredField.setAccessible(true);
            return (T) declaredField.get(o);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> void setFieldValue(T obj, String field, Object value) {
        Class<?> aClass = obj.getClass();
        try {
            Field declaredField = aClass.getDeclaredField(field);
            declaredField.setAccessible(true);
            declaredField.set(obj, value);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static <T> void setFieldValue(T obj, Field field, Object value) {
        try {
            field.setAccessible(true);
            field.set(obj, value);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
